package com.eenie.common.base.rainbow

import androidx.lifecycle.ViewModelProvider
import co.zsmb.rainbowcake.base.RainbowCakeViewModel
import co.zsmb.rainbowcake.dagger.RainbowCakeApplication
import co.zsmb.rainbowcake.dagger.RainbowCakeComponent
import com.eenie.common.base.BaseApplication

/**
 * Uses the ViewModelFactory from the [RainbowCakeComponent] inside the [RainbowCakeApplication] to
 * fetch the appropriate ViewModel instance for the Activity.
 */
public inline fun <A : BaseRainbowActivity<VS, VM>, VS, reified VM : RainbowCakeViewModel<VS>> A.getViewModelFromFactory(): VM {
    val viewModelFactory = (this.getApplicationContext() as? BaseApplication)
            ?.injector
            ?.viewModelFactory()
            ?: throw IllegalStateException("RainbowCakeActivity should not be used without an Application that inherits from RainbowCakeApplication")

    return ViewModelProvider(this, viewModelFactory).get(VM::class.java)
}